﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Mrsoft.Common;

namespace Mrsoft.Core
{
    class LocalDati : IDati
    {

        /// <summary>
        /// bool
        /// </summary>
        /// <param name="dt"></param>
        public LocalDati() {
            var url = string.Format("Tcp://{0}:13140/Dati", DatiManager.DatiSeviceHost.Value);
            this.dt = (Remote.IDati)Activator.GetObject(typeof(Remote.IDati), url);
        }

        /// <summary>
        /// 局域网答题器接口
        /// </summary>
        private Remote.IDati dt;

        public int Points {
            get { return 0; }
        }

        public bool IsReady {
            get {
                try {
                    return (dt.ConnectionTest() == "OK");
                }
                catch { return false; }
            }
        }

        public DatiResult Answer(DatiModel datiModel) {
            try {
                int questionId = dt.SendQuestion(File.ReadAllBytes(datiModel.ImageFullPath));
                DateTime nw = DateTime.Now;
                var answer = 0;

                while (answer == 0) {
                    answer = dt.GetAnswer(questionId);
                    Thread.Sleep(300);
                    if ((DateTime.Now - nw).TotalSeconds > datiModel.Timeout)
                        break;
                }

                if (answer <= 0) {
                    var r = new Random();
                    answer = r.Next(1, 4);
                }

                return new DatiResult(true, answer.ToString());
            }
            catch (Exception ex) {
                return new DatiResult(false, ex.Message);
            }
        }


    }
}
